

package com.gs.api.projects.shejiao.service;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gs.api.core.common.util.ShareCodeUtil;
import com.gs.api.projects.bzapplets.entity.BzConfig;
import com.gs.api.core.baen.pay.PayInfoDto;

import com.gs.api.core.entity.TPaymentTransaction;
import com.gs.api.core.entity.TPaymentTransactionLog;
import com.gs.api.core.service.ITPaymentTransactionLogService;
import com.gs.api.core.service.ITPaymentTransactionService;
import com.gs.api.projects.shejiao.entity.BalanceRecord;
import com.gs.api.projects.shejiao.entity.ManheConfig;
import com.gs.api.projects.shejiao.entity.TMemberUser;
import com.gs.api.projects.shejiao.entity.TTeamlevel;
import com.gs.api.util.Arith;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;


@Service
public class PayService {

    @Resource
    private Snowflake snowflake;

    @Autowired
    private IManheConfigService iManheConfigService;

    @Autowired
    private ITPaymentTransactionService itPaymentTransactionService;

    @Autowired
    private ITPaymentTransactionLogService itPaymentTransactionLogService;

    @Autowired
    private ITMemberUserService itMemberUserService;

    @Autowired
    private ITTeamlevelService itTeamlevelService;

    @Autowired
    private IBalanceRecordService iBalanceRecordService;
    /**
     * 不同的订单号，同一个支付流水号
     */
    @Transactional(rollbackFor = Exception.class)
    public PayInfoDto pay(String type,String appid) {

        ManheConfig manheConfig = iManheConfigService.getOne(new QueryWrapper<ManheConfig>().eq("appid", appid));

        // 支付单号
        String payNo = String.valueOf(snowflake.nextId());
        PayInfoDto payInfoDto = new PayInfoDto();
        payInfoDto.setPayNo(payNo);
        if("1".equals(type) || "2".equals(type)){
            //获取付款金额
            payInfoDto.setPayAmount(Double.valueOf(manheConfig.getAccessMoney().toString()));
            payInfoDto.setBody("1".equals(type) ?"盲盒纸条存入" :"盲盒纸条取出");
        }else if("3".equals(type)){
            //获取付款金额
            payInfoDto.setPayAmount(Double.valueOf(manheConfig.getMenberMoney().toString()));
            payInfoDto.setBody("成为推广会员");
        }

        return payInfoDto;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean paySuccess(String payNo, String bizPayNo,String appid) {
        TPaymentTransaction paymentTransaction = itPaymentTransactionService.getOne(new LambdaQueryWrapper<TPaymentTransaction>().eq(TPaymentTransaction::getPayNumber, payNo));

        // 订单已支付
        if (paymentTransaction.getPayStatus() == 1) {
            throw new RuntimeException("订单已支付");
        }
        paymentTransaction.setBizPayNo(bizPayNo);
        paymentTransaction.setUpdateTime(new Date());
        paymentTransaction.setPayStatus(1);
        // 将订单改为已支付状态
        boolean update = itPaymentTransactionService.updateById(paymentTransaction);

        // TODO 新增日志
        TPaymentTransactionLog paylog = new TPaymentTransactionLog();
        paylog.setAsyncLog("支付回调");
        paylog.setSynchLog("支付回调");
        paylog.setTransactionId(paymentTransaction.getId());
        paylog.setCreateTime(new Date());
        itPaymentTransactionLogService.save(paylog);

        // TODO 处理业务
        if(1 == paymentTransaction.getConsumeType() || 2 == paymentTransaction.getConsumeType()){

            String parentId = itTeamlevelService.getParentId(paymentTransaction.getUserId());
            BigDecimal profit = profit(paymentTransaction.getPayAmount(),appid);
            addBalanceRecord(parentId,paymentTransaction.getUserId(),paymentTransaction.getConsumeType(),profit,appid);

            updateBalance(profit,parentId);
        }else if(3 == paymentTransaction.getConsumeType()){
            addMemberUser(paymentTransaction.getUserId(),paymentTransaction.getConsumeType(),paymentTransaction.getPayAmount(),appid);
        }

        return update;
    }




    public void addMemberUser(String userId,Integer type,String payAmount,String appid){
        TMemberUser memberUser = itMemberUserService.getOne(new QueryWrapper<TMemberUser>().eq("user_id", userId));
        if(null == memberUser){
            TMemberUser user = new TMemberUser();
            user.setUserId(userId);
            user.setStatus(1);
            user.setAppid(appid);
            user.setCreateTime(new Date());
            user.setBalance(new BigDecimal("0"));
            itMemberUserService.save(user);
            user.setShareCode(ShareCodeUtil.toSerialCode(user.getId()));
            itMemberUserService.updateById(user);

            // 计算推广收益
            TTeamlevel teamlevel = itTeamlevelService.getOne(new QueryWrapper<TTeamlevel>().eq("user_id",user.getUserId()));
            if(null != teamlevel && StringUtils.isNotBlank(teamlevel.getParentId())){

                BigDecimal profit = profit(payAmount,appid);
                //修改用户余额
                updateBalance(profit,teamlevel.getParentId());

                addBalanceRecord(teamlevel.getParentId(),userId,type,profit,appid);
            }

        }
    }

    /**
     * 增加余额记录
     * @param parendId
     * @param userId
     * @param type
     * @param money
     */
    public void addBalanceRecord(String parendId,String userId,Integer type,BigDecimal money,String appid){
        if(!StringUtils.isNotBlank(parendId)){
            return;
        }
        //增加收益记录
        BalanceRecord balanceRecord = new BalanceRecord();
        balanceRecord.setAppid(appid);
        balanceRecord.setUserId(parendId);
        balanceRecord.setSouUserId(userId);
        balanceRecord.setMoney(money);
        balanceRecord.setSource(type);
        balanceRecord.setCreateTime(new Date());
        balanceRecord.setDataType(1);
        balanceRecord.setFlowNo(String.valueOf(snowflake.nextId()));

        if(1 == type){
            balanceRecord.setRemarks("来自用户存纸条奖励");
        }else  if(2 == type){
            balanceRecord.setRemarks("来自用户去纸条奖励");
        }else  if(3 == type){
            balanceRecord.setRemarks("来自用户开通推广会员奖励");
        }

        iBalanceRecordService.save(balanceRecord);
    }

    /**
     * 获取佣金
     * @param payAmount 支付金额
     * @return
     */
    public BigDecimal profit(String payAmount,String appid){
        ManheConfig manheConfig = iManheConfigService.getOne(new QueryWrapper<ManheConfig>().eq("appid", appid));
        BigDecimal bfb = manheConfig.getYongjin().divide(new BigDecimal("100"));
        BigDecimal divStr = Arith.mul(bfb.toString(), payAmount);
        return divStr;
    }

    /**
     * 修改用户余额
     * @param balance
     * @param openid
     */
    public void updateBalance(BigDecimal balance,String openid){
        if(!StringUtil.isNotBlank(openid)){
            return;
        }
        TMemberUser memberUser = itMemberUserService.getOne(new QueryWrapper<TMemberUser>().eq("user_id", openid));
        if(null != memberUser){

            memberUser.setBalance(new BigDecimal(String.valueOf(Arith.add(memberUser.getBalance(), balance))));

            itMemberUserService.updateById(memberUser);
        }
    }

}
